<template>
  <el-card shadow="never">
    <el-form :model="form" :rules="rulesForm" ref="refForm" label-width="80px" :inline="true">
      <el-form-item label="贷超APP" prop="appName">
        <el-select v-model="form.appName" clearable>
          <el-option v-for="item in productList" :key="item.appId" :label="item.appName"
                     :value="item.appName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" oninput="value = value.replace(/[^\d]/g, '')" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="codeConfirm">生成验证码</el-button>
      </el-form-item>
    </el-form>

    <Dialog v-model="visibleCode" title="生成验证码" @cancel="visibleCode = false" :footer="false">
      <el-form label-width="80px">
        <el-form-item label="手机号码">
          <div style="line-height: 32px">
            {{ form.phone }}
          </div>
        </el-form-item>
        <el-form-item label="验证码">
          <div style="line-height: 32px">
            <el-button type="text" @click="copyCode">{{ code }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </Dialog>
  </el-card>
</template>

<script>
import {selectProductList} from '@/api/index'
import {onMounted, reactive, ref} from "vue";
import {createSendCode} from '@/api/market'
import {ElMessage} from 'element-plus'

export default {
  name: "MarketCreateCode",
  setup() {
    const productList = ref([])
    const form = reactive({
      appName: null,
      phone: null
    })
    const refForm = ref(null)
    const visibleCode = ref(false)
    const rulesForm = reactive({
      appName: [
        {required: true, message: '请选择', trigger: 'change'},
      ],
      phone: [
        {required: true, message: '不能为空'},
      ]
    })
    const code = ref(null)

    function codeConfirm() {
      refForm.value.validate(async v => {
        if (v) {
          const res = await createSendCode(form)
          if (res.code === 200) {
            code.value = res.data
            visibleCode.value = true
          }
        }
      })
    }

    function copyCode() {
      let input = document.createElement("input");
      input.value = code.value || ''
      document.body.appendChild(input);
      input.select()
      document.execCommand('copy')
      ElMessage.success('复制成功')
      document.body.removeChild(input);
    }

    onMounted(() => {
      selectProductList({status: 1}).then(res => {
        if (res.code === 200) {
          productList.value = res.data
        }
      })
    })
    return {
      productList,
      copyCode,
      visibleCode,
      form,
      codeConfirm,
      rulesForm,
      refForm,
      code
    }
  }
}
</script>

<style scoped>

</style>
